#region Microsoft Public License
/*
 * (c) Copyright Chenjun Wu. http://utablesdk.codeplex.com
 * 
 * This source is subject to the Microsoft Public License (Ms-PL).
 * Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
 * All other rights reserved.
 */
#endregion

﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using UTable.Objects;

namespace UTable.Input
{
	public class CompositeProvider : IInputProvider
	{
		private ObservableCollection<IInputProvider> _providers;

		public CompositeProvider()
		{
			_providers = new ObservableCollection<IInputProvider>();
			_providers.CollectionChanged += new NotifyCollectionChangedEventHandler(Providers_CollectionChanged);
		}

		void Providers_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			switch (e.Action)
			{
				case NotifyCollectionChangedAction.Add:
					OnProviderAdded(e.NewItems[0] as IInputProvider);
					break;
				case NotifyCollectionChangedAction.Remove:
					OnProviderRemoved(e.OldItems[0] as IInputProvider);
					break;
				case NotifyCollectionChangedAction.Replace:
					OnProviderRemoved(e.OldItems[0] as IInputProvider);
					OnProviderAdded(e.NewItems[0] as IInputProvider);
					break;
				case NotifyCollectionChangedAction.Reset:
					break;
			}
		}

		void OnProviderAdded(IInputProvider provider)
		{
            provider.InputTriggered += provider_InputTriggered;
		}

		void OnProviderRemoved(IInputProvider provider)
		{
            provider.InputTriggered -= provider_InputTriggered;
		}

		void provider_InputTriggered(InputEventArgs args)
		{
			if (InputTriggered != null)
				InputTriggered(args);
		}

		public Collection<IInputProvider> Providers { get { return _providers; } }



		#region IInputProvider Members

		public event InputEventHandler InputTriggered;

        public void Initialize(UApplication context)
        {
            // do nothing
        }

		#endregion
	}
}
